import paramiko
import psycopg2
import json
import datetime
import re
import os

# get sentinel2 tile list
def get_tiles(province):
	con = psycopg2.connect(
	database="sentinel2",
	user="postgres",
	password="12345",
	host="192.168.2.172",
	port="5432"
	)
	cur = con.cursor()
	sql = f"""
	SELECT "中国有效哨兵格网分布wgs84".mgrs
	FROM china_sy
	JOIN "中国有效哨兵格网分布wgs84" 
	on st_intersects(china_sy.geom,"中国有效哨兵格网分布wgs84".geom)
	WHERE  china_sy.qhmc = '{province}' 
	"""
	cur.execute(sql)
	con.commit()
	tiles=[record[0] for record in cur.fetchall()]
	tiles = [tile.upper() for tile in tiles]
	cur.close()
	con.close()
	return tiles

# start
def main():
    print("GY100KM,GY10KM数据切片工具！")
    json_path = r"E:\PythonProjcet\RasterShapeToolBox\conf\ChinaMgrs.json"
    province = input("请输入省份(必选,例如：河南省): ")
    if province == "":
        tiles = input("请输入图幅列表（例如：49slh-50sds）：")
        while tiles == "":
            tiles = input("请输入图幅列表（例如：49slh-50sds）：")
    else:
        # tiles = get_tiles(province)
        with open(json_path, "r", encoding="utf-8") as json_file:
            china_tiles = json.load(json_file)
        tiles = china_tiles[province]
        tiles = "-".join(tiles)
    year = input("请输入年份（必选, 例如：2022）：")
    while year == "":
        year = input("请输入年份（必选, 例如：2022）：")
    month = input("请输入月份（必选, 例如：3）：")
    while month == "":
        month = input("请输入月份（必选, 例如：3）：")
    period = input("请输入时期（默认：3000）：")
    if period == "":
        period = "3000"
    bands = input("请输入波段列表（默认：2-3-4-5-6-7-8-8A-11-12-99）：")
    if bands == "":
        bands = "2-3-4-5-6-7-8-8A-11-12-99"
    folder = input("请输入82服务器上L3A目录（必选）：")
    while folder == "":
        folder = input("请输入82服务器上L3A目录（必选）：")
    python_path = r"/home/fengyangyang/python_env_1/bin/python"
    script_path = r"/home/fengyangyang/projection_1/L3aRaster2Gykm.py"
    params = [
        f"{python_path}",
        f"{script_path}",
        f"--tiles {tiles}",
        f"--year {year}",
        f"--month {month}",
        f"--period {period}",
        f"--bands {bands}",
        f"--folder {folder}"
    ]
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
    ssh.connect(
        hostname="192.168.1.82",
        port="22",
        username="root",
        password="000000")
    command = " ".join(params)
    stdin, stdout, stderr = ssh.exec_command(command,get_pty=True)
    for line in iter(stdout.readline,""): 
        print(line)
    ssh.close()
    return



if __name__ == "__main__":
    main()